/*******************************************************************************
 * Copyright (c) 2004, 2009 Blue Bamboo International Inc. 
 * All rights reserved.
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *******************************************************************************/

package com.bambamboo.socket.server.mina;

import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bambamboo.socket.server.AbstractIOServer;
import com.bambamboo.socket.server.ServerConfigurationBean;

/**
 * DOCME
 * 
 * @author Nick.Tan
 * @since 1.1
 */
public class SerialServer extends AbstractIOServer {

	private static final Logger logger = LoggerFactory.getLogger(SerialServer.class);

	@Override
	public void startup() throws Exception {
		SerialConnector connector = new SerialConnector();
		ServerConfigurationBean bean = getServerConfigurationBean();
		BaseIoHandler iohandler = null;
		String handlerClassname = bean.getHandler();
		if (handlerClassname == null || handlerClassname.trim().length() == 0) {
			iohandler = new DefaultIoHandler();
		}
		else {
			Class ioHandlerClazz = Class.forName(bean.getHandler());
			iohandler = (BaseIoHandler) ioHandlerClazz.newInstance();
		}
		iohandler.setConfigurationBean(bean);
		connector.setHandler(iohandler);
		String port = bean.getPort();
		try {
			connector.connect(new SerialAddress(port, 115200,
					org.apache.mina.transport.serial.SerialAddress.DataBits.DATABITS_8,
					org.apache.mina.transport.serial.SerialAddress.StopBits.BITS_1,
					org.apache.mina.transport.serial.SerialAddress.Parity.NONE,
					org.apache.mina.transport.serial.SerialAddress.FlowControl.RTSCTS_IN));
			logger.info(String.format(">>> listening on serial port [%s]", port));
		}
		catch (Exception e) {
			// catch to continue binding other ports
			logger.error(String.format(">>> binding on serial port [%s] failure!", port), e);
		}
	}

}
